﻿//-----------------------------------------------------------------------
// <copyright company="www.3WayWebdesign.de">
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//
// <author>Michael Morbach</author>
// <email>Michael@3waywebdesign.de</email>
// <web>http://www.3waywebdesign.de</web>
//-----------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using Tww.Wpf.Controls.Native;

namespace Tww.Wpf.Controls.Controls.Windows
{
    public class WindowSettings
    {
        #region  - Felder (öffentlich) -

        public static readonly DependencyProperty WindowPlacementSettingsProperty =
            DependencyProperty.RegisterAttached("WindowPlacementSettings", typeof (IWindowPlacementSettings),
                typeof (WindowSettings), new FrameworkPropertyMetadata(OnWindowPlacementSettingsInvalidated));

        #endregion

        #region  - Felder (privat) -

        private IWindowPlacementSettings _settings;
        private Window _window;

        #endregion

        #region  - Konstruktoren -

        public WindowSettings(Window window, IWindowPlacementSettings windowPlacementSettings)
        {
            _window = window;
            _settings = windowPlacementSettings;
        }

        #endregion

        #region  - Methoden (öffentlich) -

        public static void SetSave(DependencyObject dependencyObject, IWindowPlacementSettings windowPlacementSettings)
        {
            dependencyObject.SetValue(WindowPlacementSettingsProperty, windowPlacementSettings);
        }

        #endregion

        #region  - Methoden (privat) -

        private static void OnWindowPlacementSettingsInvalidated(DependencyObject dependencyObject,
            DependencyPropertyChangedEventArgs e)
        {
            var window = dependencyObject as Window;
            if (window == null || !(e.NewValue is IWindowPlacementSettings)) return;

            var windowSettings = new WindowSettings(window, (IWindowPlacementSettings) e.NewValue);
            windowSettings.Attach();
        }

        protected virtual void LoadWindowState()
        {
            if (_settings == null) return;
            _settings.Reload();

            if (_settings.Placement == null) return;

            try
            {
                WINDOWPLACEMENT wp = _settings.Placement.Value;

                wp.length = Marshal.SizeOf(typeof (WINDOWPLACEMENT));
                wp.flags = 0;
                wp.showCmd = (wp.showCmd == Constants.SW_SHOWMINIMIZED ? Constants.SW_SHOWNORMAL : wp.showCmd);
                IntPtr hwnd = new WindowInteropHelper(_window).Handle;
                UnsafeNativeMethods.SetWindowPlacement(hwnd, ref wp);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to load window state:\r\n{0}", ex);
            }
        }

        protected virtual void SaveWindowState()
        {
            if (_settings == null) return;
            WINDOWPLACEMENT wp;
            IntPtr hwnd = new WindowInteropHelper(_window).Handle;
            UnsafeNativeMethods.GetWindowPlacement(hwnd, out wp);
            _settings.Placement = wp;
            _settings.Save();
        }

        private void Attach()
        {
            if (_window == null) return;
            _window.Closing += WindowClosing;
            _window.SourceInitialized += WindowSourceInitialized;
        }

        private void WindowSourceInitialized(object sender, EventArgs e)
        {
            LoadWindowState();
        }

        private void WindowClosing(object sender, CancelEventArgs e)
        {
            SaveWindowState();
            _window.Closing -= WindowClosing;
            _window.SourceInitialized -= WindowSourceInitialized;
            _window = null;
            _settings = null;
        }

        #endregion
    }
}